import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../providers/anime_provider.dart';
import '../../domain/entities/anime.dart';
import '../../core/utils/chinese_title_mapper.dart';

/// 搜索页面
class SearchPage extends StatefulWidget {
  const SearchPage({super.key});

  @override
  State<SearchPage> createState() => _SearchPageState();
}

class _SearchPageState extends State<SearchPage> with AutomaticKeepAliveClientMixin {
  final TextEditingController _searchController = TextEditingController();
  final ScrollController _scrollController = ScrollController();
  
  List<Anime> _searchResults = [];
  bool _isSearching = false;
  bool _hasSearched = false;
  bool _hasMoreData = true;
  int _currentPage = 1;
  String _currentQuery = '';
  
  // 专题相关参数
  String? _topicTitle;
  String? _topicSubtitle;
  bool _isTopicSearch = false;

  @override
  bool get wantKeepAlive => true;

  @override
  void initState() {
    super.initState();
    _scrollController.addListener(_onScroll);
    
    // 在下一帧初始化路由参数
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _initializeWithRouteArgs();
    });
  }

  @override
  void dispose() {
    _searchController.dispose();
    _scrollController.dispose();
    super.dispose();
  }

  void _onScroll() {
    if (_scrollController.position.pixels >= 
        _scrollController.position.maxScrollExtent - 80) {
      if (!_isSearching && _hasMoreData && _currentQuery.isNotEmpty) {
        _loadMoreResults();
      }
    }
  }

  void _initializeWithRouteArgs() {
    final args = ModalRoute.of(context)?.settings.arguments as Map<String, dynamic>?;
    if (args != null) {
      final query = args['query'] as String?;
      final title = args['title'] as String?;
      final subtitle = args['subtitle'] as String?;
      
      if (query != null && query.isNotEmpty) {
        _searchController.text = query;
        _topicTitle = title;
        _topicSubtitle = subtitle;
        _isTopicSearch = true;
        
        // 自动执行搜索
        _performSearch();
      }
    }
  }

  Future<void> _performSearch({bool isNewSearch = true}) async {
    final query = _searchController.text.trim();
    if (query.isEmpty) return;

    setState(() {
      _isSearching = true;
      if (isNewSearch) {
        _currentQuery = query;
        _currentPage = 1;
        _searchResults.clear();
        _hasMoreData = true;
      }
    });

    try {
      final provider = Provider.of<AnimeProvider>(context, listen: false);
      final results = await provider.searchAnime(
        _currentQuery,
        page: _currentPage,
      );
      
      setState(() {
        if (isNewSearch) {
          _searchResults = results;
        } else {
          _searchResults.addAll(results);
        }
        _hasSearched = true;
        _hasMoreData = results.length >= 20; // 如果返回少于20个结果，说明没有更多了
        _isSearching = false;
      });
    } catch (e) {
      setState(() {
        _isSearching = false;
      });
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('搜索失败: $e')),
        );
      }
    }
  }

  Future<void> _loadMoreResults() async {
    _currentPage++;
    await _performSearch(isNewSearch: false);
  }

  void _clearSearch() {
    _searchController.clear();
    setState(() {
      _searchResults.clear();
      _hasSearched = false;
      _currentQuery = '';
      _currentPage = 1;
      _hasMoreData = true;
    });
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    
    return Scaffold(
      backgroundColor: const Color(0xFFF5F7FA),
      appBar: AppBar(
        title: _isTopicSearch && _topicTitle != null 
            ? Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisSize: MainAxisSize.min,
                children: [
                  Text(
                    _topicTitle!,
                    style: const TextStyle(
                      fontSize: 18,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  if (_topicSubtitle != null)
                    Text(
                      _topicSubtitle!,
                      style: const TextStyle(
                        fontSize: 12,
                        fontWeight: FontWeight.normal,
                        color: Colors.grey,
                      ),
                    ),
                ],
              )
            : const Text('搜索'),
        backgroundColor: Colors.white,
        elevation: 0,
        centerTitle: false,
      ),
      body: Column(
        children: [
          // 搜索框
          Container(
            color: Colors.white,
            padding: const EdgeInsets.all(16),
            child: TextField(
              controller: _searchController,
              decoration: InputDecoration(
                hintText: '搜索动漫名称...',
                prefixIcon: const Icon(Icons.search),
                suffixIcon: IconButton(
                  icon: const Icon(Icons.clear),
                  onPressed: _clearSearch,
                ),
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(25),
                  borderSide: BorderSide.none,
                ),
                filled: true,
                fillColor: const Color(0xFFF5F7FA),
                contentPadding: const EdgeInsets.symmetric(
                  horizontal: 20,
                  vertical: 12,
                ),
              ),
              onSubmitted: (value) => _performSearch(),
              textInputAction: TextInputAction.search,
            ),
          ),
          
          // 搜索结果或空状态
          Expanded(
            child: _buildContent(),
          ),
        ],
      ),
    );
  }

  Widget _buildContent() {
    if (_isSearching && _searchResults.isEmpty) {
      return const Center(child: CircularProgressIndicator());
    }

    if (!_hasSearched) {
      return _buildEmptyState();
    }

    if (_searchResults.isEmpty) {
      return _buildNoResults();
    }

    return _buildSearchResults();
  }

  Widget _buildEmptyState() {
    return const Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            Icons.search,
            size: 64,
            color: Colors.grey,
          ),
          SizedBox(height: 16),
          Text(
            '搜索你喜欢的动漫',
            style: TextStyle(
              fontSize: 16,
              color: Colors.grey,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildNoResults() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          const Icon(
            Icons.search_off,
            size: 64,
            color: Colors.grey,
          ),
          const SizedBox(height: 16),
          Text(
            '未找到相关动漫',
            style: TextStyle(
              fontSize: 16,
              color: Colors.grey[600],
            ),
          ),
          const SizedBox(height: 8),
          Text(
            '尝试使用其他关键词搜索',
            style: TextStyle(
              fontSize: 14,
              color: Colors.grey[500],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildSearchResults() {
    return CustomScrollView(
      controller: _scrollController,
      slivers: [
        // 搜索结果统计
        SliverToBoxAdapter(
          child: Container(
            padding: const EdgeInsets.all(16),
            child: Text(
              '找到 ${_searchResults.length} 个结果',
              style: TextStyle(
                fontSize: 14,
                color: Colors.grey[600],
              ),
            ),
          ),
        ),

        // 搜索结果列表 - 添加错误边界保护
        SliverList(
          delegate: SliverChildBuilderDelegate(
            (context, index) {
              // 添加索引边界检查
              if (index >= _searchResults.length) {
                return const SizedBox.shrink();
              }
              
              try {
              final anime = _searchResults[index];
                // 确保动漫数据有效
                if (anime.id <= 0 || anime.title.isEmpty) {
                  return const SizedBox.shrink();
                }
              return _buildSearchResultItem(anime);
              } catch (e) {
                // 如果单个item渲染失败，显示错误占位符
                print('搜索结果项渲染错误: $e');
                return Container(
                  margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
                  padding: const EdgeInsets.all(16),
                  child: Text(
                    '该项数据无法显示',
                    style: TextStyle(color: Colors.grey[600]),
                  ),
                );
              }
            },
            childCount: _searchResults.length,
          ),
        ),

        // 加载更多指示器
        if (_isSearching && _searchResults.isNotEmpty)
          const SliverToBoxAdapter(
            child: Padding(
              padding: EdgeInsets.all(16),
              child: Center(child: CircularProgressIndicator()),
            ),
          ),

        // 无更多数据提示
        if (!_hasMoreData && _searchResults.isNotEmpty)
          const SliverToBoxAdapter(
            child: Padding(
              padding: EdgeInsets.all(16),
              child: Center(
                child: Text(
                  '没有更多结果了',
                  style: TextStyle(color: Colors.grey),
                ),
              ),
            ),
          ),

        const SliverToBoxAdapter(child: SizedBox(height: 20)),
      ],
    );
  }

  Widget _buildSearchResultItem(Anime anime) {
    if (anime.id == 0) {
      return const SizedBox.shrink();
    }

    final chineseTitle = ChineseTitleMapper.getBestChineseTitle(
      title: anime.title,
      titleJapanese: anime.titleJapanese,
      titleEnglish: anime.titleEnglish,
      titleSynonyms: anime.titleSynonyms,
    );
    final chineseGenres = ChineseTitleMapper.getChineseGenres(anime.genres);

    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 6),
      child: Card(
        elevation: 2,
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
        child: InkWell(
          borderRadius: BorderRadius.circular(12),
          onTap: () {
            Navigator.pushNamed(
              context,
              '/detail',
              arguments: {'id': anime.id},
            );
          },
          child: Padding(
            padding: const EdgeInsets.all(16),
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // 动漫封面
                Container(
                  width: 90,
                  height: 135,
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(8),
                    color: Colors.grey[300],
                    boxShadow: [
                      BoxShadow(
                        color: Colors.black.withOpacity(0.1),
                        blurRadius: 4,
                        offset: const Offset(0, 2),
                      ),
                    ],
                  ),
                  child: ClipRRect(
                    borderRadius: BorderRadius.circular(8),
                      child: anime.imageUrl.isNotEmpty
                          ? Image.network(
                              anime.imageUrl,
                              fit: BoxFit.cover,
                            width: 90,
                            height: 135,
                            loadingBuilder: (context, child, loadingProgress) {
                              if (loadingProgress == null) return child;
                              return Container(
                                width: 90,
                                height: 135,
                                color: Colors.grey[200],
                                child: const Center(
                                  child: CircularProgressIndicator(strokeWidth: 2),
                                ),
                              );
                            },
                              errorBuilder: (context, error, stackTrace) {
                                return Container(
                                width: 90,
                                height: 135,
                                color: Colors.grey[200],
                                child: const Icon(Icons.image_not_supported, size: 32),
                                );
                              },
                            )
                          : Container(
                            width: 90,
                            height: 135,
                            color: Colors.grey[200],
                            child: const Icon(Icons.image, size: 32),
                    ),
                  ),
                ),
                const SizedBox(width: 16),
                
                // 动漫详细信息
                Flexible(
                  child: Container(
                    height: 135,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                        // 标题和年份
                        Row(
                          children: [
                            Expanded(
                              child: Text(
                                chineseTitle.isNotEmpty ? chineseTitle : '未知标题',
                        style: const TextStyle(
                                  fontSize: 17,
                          fontWeight: FontWeight.bold,
                                  height: 1.2,
                        ),
                        maxLines: 2,
                        overflow: TextOverflow.ellipsis,
                              ),
                            ),
                            if (anime.year != null)
                              Container(
                                padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
                                decoration: BoxDecoration(
                                  color: Colors.blue.withOpacity(0.1),
                                  borderRadius: BorderRadius.circular(4),
                                ),
                                child: Text(
                                  '${anime.year}',
                                  style: TextStyle(
                                    fontSize: 11,
                                    color: Colors.blue[700],
                                    fontWeight: FontWeight.w500,
                                  ),
                                ),
                              ),
                          ],
                      ),
                      const SizedBox(height: 8),
                        
                        // 类型标签
                      if (chineseGenres.isNotEmpty)
                          Wrap(
                            spacing: 4,
                            runSpacing: 4,
                            children: chineseGenres.take(4).map((genre) => Container(
                              padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
                              decoration: BoxDecoration(
                                color: Colors.purple.withOpacity(0.1),
                                borderRadius: BorderRadius.circular(4),
                              ),
                              child: Text(
                                genre,
                                style: TextStyle(
                                  fontSize: 10,
                                  color: Colors.purple[700],
                                  fontWeight: FontWeight.w500,
                                ),
                              ),
                            )).toList(),
                          ),
                        const SizedBox(height: 8),
                        
                        // 简介预览
                        if (anime.synopsis.isNotEmpty && anime.synopsis != '暂无简介')
                          Expanded(
                            child: Text(
                              anime.synopsis,
                          style: TextStyle(
                            fontSize: 12,
                                color: Colors.grey[700],
                                height: 1.3,
                              ),
                              maxLines: 3,
                              overflow: TextOverflow.ellipsis,
                          ),
                        ),
                        
                        const Spacer(),
                        
                        // 底部信息栏
                      Row(
                        children: [
                            // 评分
                          if (anime.score > 0) ...[
                            Icon(Icons.star, color: Colors.amber, size: 16),
                              const SizedBox(width: 2),
                            Text(
                              anime.score.toStringAsFixed(1),
                              style: const TextStyle(
                                  fontSize: 13,
                                fontWeight: FontWeight.w600,
                                  color: Colors.amber,
                              ),
                            ),
                              const SizedBox(width: 12),
                            ],
                            
                            // 集数信息
                            if (anime.episodes > 0) ...[
                              Icon(Icons.tv, size: 14, color: Colors.grey[600]),
                              const SizedBox(width: 2),
                              Text(
                                '${anime.episodes}话',
                                style: TextStyle(
                                  fontSize: 11,
                                  color: Colors.grey[600],
                                ),
                              ),
                              const SizedBox(width: 12),
                            ],
                            
                            // 制作公司（如果有）
                            if (anime.studios.isNotEmpty) ...[
                              Icon(Icons.business, size: 14, color: Colors.grey[600]),
                              const SizedBox(width: 2),
                              Expanded(
                                child: Text(
                                  anime.studios.first,
                                  style: TextStyle(
                                    fontSize: 11,
                                    color: Colors.grey[600],
                                  ),
                                  maxLines: 1,
                                  overflow: TextOverflow.ellipsis,
                                ),
                              ),
                            ],
                            
                            const Spacer(),
                            
                            // 状态标签
                          Container(
                            padding: const EdgeInsets.symmetric(
                                horizontal: 8,
                                vertical: 4,
                            ),
                            decoration: BoxDecoration(
                                color: _getStatusColor(anime.status ?? '').withOpacity(0.1),
                                borderRadius: BorderRadius.circular(6),
                                border: Border.all(
                                  color: _getStatusColor(anime.status ?? '').withOpacity(0.3),
                                  width: 1,
                                ),
                            ),
                            child: Text(
                                _getStatusText(anime.status ?? ''),
                              style: TextStyle(
                                fontSize: 10,
                                  color: _getStatusColor(anime.status ?? ''),
                                  fontWeight: FontWeight.w600,
                                ),
                              ),
                            ),
                          ],
                          ),
                        ],
                      ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Color _getStatusColor(String status) {
    switch (status.toLowerCase()) {
      case 'currently airing':
        return Colors.green;
      case 'finished airing':
        return Colors.blue;
      case 'not yet aired':
        return Colors.orange;
      default:
        return Colors.grey;
    }
  }

  String _getStatusText(String status) {
    switch (status.toLowerCase()) {
      case 'currently airing':
        return '连载中';
      case 'finished airing':
        return '已完结';
      case 'not yet aired':
        return '未播出';
      default:
        return status;
    }
  }
} 